﻿namespace ERAIconHandler
{
    using System;
    using System.Drawing;
    using System.IO;
    using System.Runtime.InteropServices;

    using EFML_Runtime;

    using SharpShell.Attributes;
    using SharpShell.SharpIconHandler;

    using global::ERAIconHandler.Properties;

    /// <summary>
    /// 	The DllIconHandler is a Shell Icon Handler exception that
    /// 	shows different icons for native and managed dlls.
    /// </summary>
    [ComVisible(true)]
    [COMServerAssocation(AssociationType.ClassOfExtension, ".era")]
    public class ERAIconHandler : SharpIconHandler
    {
        #region Methods

        /// <summary>
        /// 	Gets the icon.
        /// </summary>
        /// <param name="smallIcon"> if set to <c>true</c> provide a small icon. </param>
        /// <param name="iconSize"> Size of the icon. </param>
        /// <returns> The icon for the file. </returns>
        protected override Icon GetIcon(bool smallIcon, uint iconSize)
        {
            //  The icon we'll return.
            Icon icon = null;

            //  Check the assembly name. If it's a native dll, this'll throw an exception.
            try
            {
                var e = new Exeutable();
                e.Load(new FileStream(this.SelectedItemPath, FileMode.OpenOrCreate));
                icon = new Icon(new MemoryStream(e.Info.Icon));
            }
            catch (ArgumentException ex)
            {
                //File.WriteAllText("log.txt", ex.Message + "\r" + SelectedItemPath);
                //Process.Start("log.txt");
            }

            if (icon == null)
            {
                icon = Resources.USER32_105;
            }

            //  Return the icon with the correct size. Use the SharpIconHandler 'GetIconSpecificSize'
            //  function to extract the icon of the required size.
            return GetIconSpecificSize(icon, new Size((int)iconSize, (int)iconSize));
        }

        #endregion
    }
}